/**
 * @file: service.js
 * @description:
 * @author: YUWENJING
 * @date: 2020/2/14
 * @contact:wenjingyuer@126.com
 */
import Taro from "@tarojs/taro";
import {goHome, toast} from "../../../utils";
import Envs from '../../../constant/envs'
import {getGlobalData, setGlobalData} from "../../../global.d";
const db = Taro.cloud.database();
const _ = db.command

/**
 * @description: 根据密钥、学校名称查询并加入班级
 * @author: YUWENJING
 * @date: 2020/2/14
 * @param classKey
 * @param school
 */

export function queryClassAndJoin(classKey,school) {
  if(checkIfJoinedClass(classKey)) {
    toast('你已经加入过该班级了')
    return
  }
  db.collection('class')
    .where({
      classKey:classKey
    })
    .get()
    .then(
      async res => {
        console.log(res)
        await pushUserIntoClass(res,classKey,school)
      }
    )
}

/**
 * @description: 检查是否重复加入班级
 * @author: YUWENJING
 * @date: 2020/2/14
 * @param classKey
 */

function checkIfJoinedClass(classKey) {
  let flag = false
  const user = getGlobalData('user')
 const userClass  = user.userClass
      userClass.map((item,index)=>{
        console.log(item.classKey)
        if(item.classKey===classKey)
         flag  = true
      })
  return flag
}

/**
 * @description: 将用户插入班级学生列表
 * @author: YUWENJING
 * @date: 2020/2/14
 * @param res
 * @param classKey
 * @param school
 */

 function pushUserIntoClass(res,classKey,school) {
   const user = getGlobalData('user')
  const targetClass  = res.data[0]
  console.log(targetClass)
  if(!targetClass||targetClass.classInfo.school!==school){
    toast('加入失败，检查学校名称或班级密钥！')
  }else {
    Taro.cloud.callFunction({
      name:'addUserIntoClass',
      data:{
        env: Envs.current,
        classId:targetClass._id,
        user
      }
    })
     pushClassIntoUser(user,targetClass)

  }
}

/**
 * @description: 将班级插入用户班级列表,设为最近登陆班级
 * @author: YUWENJING
 * @date: 2020/2/14
 * @param user
 * @param targetClass
 */
  function pushClassIntoUser(user,targetClass) {
    let classItem = {
      classKey:targetClass.classKey,
      type:'user',
      className:targetClass.classInfo.school+targetClass.classInfo.majorOrClassName+targetClass.classInfo.classNumber
    }
    db.collection('user')
      .doc(user._id)
      .update({
        data:{
          userClass:_.push(classItem),
          userLastTimeClass:classItem
        },
        success:res => {
          toast('加入成功！')
          goHome()
        }
      })
  }
